import { handleActions } from 'redux-actions'
import { SET_CARTS, ADD_PRODUCT_TO_LOCALCART, DELETE_CART_FROM_LOCAL, CHANGE_LOCAL_CART_COUNT } from '../actions/cart.action'

const initialState = []

export default handleActions({
  [SET_CARTS]: (state, action) => {
    console.log(action, 'cart action')
    return action.payload
  },
  [ADD_PRODUCT_TO_LOCALCART]: (state, action) => {
    const newState = JSON.parse(JSON.stringify(state))
    const hasGood = newState.find(item => item.id === action.payload.id)
    if (hasGood) {
      hasGood.count++
    } else {
      newState.push(action.payload)
    }
    return newState
  },
  [DELETE_CART_FROM_LOCAL]: (state, action) => {
    const newState = JSON.parse(JSON.stringify(state))
    console.log(action.payload, 'delete')
    newState.splice(action.payload, 1)
    return newState
  },
  [CHANGE_LOCAL_CART_COUNT]: (state, action) => {
    const newState = JSON.parse(JSON.stringify(state))
    const index = newState.findIndex(item => item.id === action.payload.id)
    console.log(index, 'index')
    if(index !== undefined) {
      newState[index] = action.payload
    }
    console.log(newState, 'state')
    return newState
  }
}, initialState)